import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import Loading from 'widget/Loading';
import ReplyService from 'service/RequestServices/ReplyService';
import PopupCard from './PopupCard';
import TextCard from './TextCard';

const Container = styled.div`
  margin-bottom: 12px;
`;

class ReplyCard extends PureComponent {
  state = {
    loading: false,
    content: '',
    replied: false
  };

  handleSubmit = content => {
    let { loading } = this.state;
    loading = true;
    this.setState(
      {
        loading
      },
      () => {
        this.reply(content);
      }
    );
  };

  reply = content => {
    const { commentID, to } = this.props;
    let { loading, replied } = this.state;
    loading = true;

    ReplyService.postReply({
      commentID,
      content,
      type: 0,
      replyToProfileID: to.id
    }).then(() => {
      loading = false;
      replied = true;
      this.setState({
        loading,
        replied,
        content
      });
    });
  };

  render() {
    const { to } = this.props;
    const { loading, replied } = this.state;

    if (loading) {
      return <Loading />;
    }

    if (replied) {
      return (
        <Container>
          <PopupCard>{this.state.content}</PopupCard>
        </Container>
      );
    }

    return (
      <TextCard
        autofocus
        {...this.props}
        placeholder={`@${to.name}`}
        onSubmit={content => this.handleSubmit(content)}
      />
    );
  }
}

ReplyCard.propTypes = {
  commentID: PropTypes.number.isRequired,
  to: PropTypes.shape({
    id: PropTypes.number.isRequired,
    name: PropTypes.string.isRequired
  }).isRequired
};

export default ReplyCard;
